package com.mingren.api.imagesearch.sub;

import com.mingren.exception.BusinessException;
import com.mingren.exception.ErrorCode;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 根据得到的url地址进一步解析 step2 获取firstUrl地址->下一步请求该地址就可获得相似图片的json数据
 */
@Slf4j
public class GetImageFirstUrlApi {

    /**
     * 获取图片列表页面地址
     *
     * @param url
     * @return
     */
    public static String getImageFirstUrl(String url) {
        try {
            //根据上一步得到的url发起请求解析hTML文档
            Document document = Jsoup.connect(url).timeout(5000).get(); //得到DOM结点
            //解析DOM结点
            //1、获取所有的script标签
            Elements scriptElements = document.getElementsByTag("script");
            //遍历找到包含firstUrl的脚本内容
            for (Element script : scriptElements) {
                String scriptContent = script.html();
                if (scriptContent.contains("\"firstUrl\"")) {
                    //如果当前脚本包含fristUrl标签的话 提取firstUrl的值
                    Pattern pattern = Pattern.compile("\"firstUrl\"\\s*:\\s*\"(.*?)\"");
                    //匹配脚本内容
                    Matcher matcher = pattern.matcher(scriptContent);
                    if (matcher.find()) {
                        //获取匹配的第一个分组内容
                        String firstUrl = matcher.group(1);
                        // 处理转义字符
                        firstUrl = firstUrl.replace("\\/", "/");
                        return firstUrl;
                    }
                }
            }
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "未找到 url");
        } catch (Exception e) {
            log.error("搜索失败", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "搜索失败");
        }
    }

    public static void main(String[] args) {
        // 请求目标 URL
        String url = "https://graph.baidu.com/s?card_key=&entrance=GENERAL&extUiData[isLogoShow]=1&f=all&isLogoShow=1&session_id=7375418200918191941&sign=1218ce97cd54acd88139901741266583&tpl_from=pc";
        String imageFirstUrl = getImageFirstUrl(url);
        System.out.println("搜索成功，结果 URL：" + imageFirstUrl);
    }
}
